﻿@model Live
@{
    Layout = null;
}
<!DOCTYPE html>
<!--HTML5 doctype-->
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
    <title>直播购物(测试版)</title>
    <link rel="stylesheet" type="text/css" href="/mobile/css/style.css" />
    <script type="text/javascript" charset="utf-8" src="/mobile/js/zepto.min.js"></script>
    <script type="text/javascript" charset="utf-8" src="/mobile/js/weui.min.js"></script>
    <script type="text/javascript" charset="utf-8" src="/mobile/js/common.js"></script>
    <script src="~/signalr/dist/browser/signalr.min.js"></script>    
</head>

<body ontouchstart>
    <div class="page">
        <!--页面头部-->
        <div class="header">
            <a class="back" href="javascript:history.back();">
                <i class="iconfont icon-arrow-left"></i>
            </a>
            <h3>直播中心</h3>
            <div class="right">
                <a class="weui-cell_access weui-cell_link" asp-area="Web" asp-controller="Usercenter" asp-action="Index" asp-route-act="index">
                    <i class="iconfont icon-user"></i>
                </a>
            </div>
        </div>
        <!--/页面头部-->

        <div class="page__bd">

            <!--直播功能-->
            <link rel="stylesheet" href="/zjego/assets/bootstrap.min.css">
            <style>
                video {
                    width: 100%;
                    height: auto;
                }


                #previewLabel {
                    display: block;
                    position: absolute;
                }
            </style>


            <div class="weui-form-preview" style="margin-top:0px;">
                <div class="container">

                    <div class="row" style="margin-top:1%;display:none">

                        <div class="col-sm">
                            <div class="input-group input-group-sm mb-3">
                                <div class="input-group-prepend">
                                    <label class="input-group-text" for="audioList"><strong class="text-gray-dark">音频设备</strong></label>
                                </div>
                                <select class="custom-select" id="audioList" style="width: 60%">
                                </select>
                            </div>
                        </div>

                        <div class="col-sm">
                            <div class="input-group input-group-sm mb-3">
                                <div class="input-group-prepend">
                                    <label class="input-group-text" for="videoList"><strong class="text-gray-dark">视频设备</strong></label>
                                </div>
                                <select class="custom-select" id="videoList" style="width: 60%">
                                </select>
                            </div>
                        </div>

                        <div class="col-sm">
                            <div class="input-group input-group-sm mb-3">
                                <div class="input-group-prepend">
                                    <label class="input-group-text" for="roomId"><strong class="text-gray-dark">房间号</strong></label>
                                </div>
                                <input type="email" class="form-control d-inline" id="roomId" style="width: 60%" aria-describedby="emailHelp" value="@Model.user_id"
                                       placeholder="请输入房间号">
                            </div>
                        </div>


                        <div class="col-sm">
                            <div class="input-group input-group-sm mb-3">
                                <div class="input-group-prepend">
                                    <label class="input-group-text" for="videoList"><strong class="text-gray-dark">推流质量</strong></label>
                                </div>
                                <select class="custom-select" id="videoQuality" style="width: 70%">
                                    <option value="1">标清</option>
                                    <option value="2">高清</option>
                                    <option value="3">超清</option>
                                </select>
                            </div>
                        </div>

                        <div class="col-sm">
                            <div class="input-group input-group-sm mb-3">
                                <div class="input-group-prepend">
                                    <label class="input-group-text" for="videoList"><strong class="text-gray-dark">最大拉流数</strong></label>
                                </div>
                                <input type="email" class="form-control d-inline" id="maxPullNamber" style="width: 75%" value="7"
                                       aria-describedby="emailHelp" placeholder="最大拉流数默认为4">
                            </div>
                        </div>

                    </div>


                    <div class="row videoRow">
                        <div class="col-sm">
                            <label id="previewLabel" class="text-white"></label>
                            <video id="previewVideo" autoplay muted playsinline></video>
                        </div>
                        <div class="col-sm remoteVideo">
                            <!-- <video  autoplay muted playsinline></video> -->
                        </div>
                    </div>
                    <div class="row">

                        <div class="col-sm">
                            <div class="input-group input-group-sm mb-3">
                                <div class="input-group-prepend">
                                    <label class="input-group-text" for="memberList"><strong class="text-gray-dark">房间人员</strong></label>
                                </div>
                                <select class="custom-select" id="memberList" style="width: 60%">
                                </select>
                            </div>
                        </div>

                    </div>
                    <div class="row">
                        <div class="col-sm">
                            <ul id="msgs">
                            </ul>
                            <div class="input-group input-group-sm mb-3">
                                <div class="input-group-prepend">
                                    <input type="button" id="btnSend" class="weui-btn weui-btn_mini" value="群聊" />
                                </div>
                                <input type="email" class="form-control d-inline" id="txtMsg" style="width: 75%"
                                       aria-describedby="emailHelp" placeholder="输入内容">
                            </div>
                        </div>                        
                    </div>
                    <div class="row">
                        <div class="col-sm">
                            <button type="button" id="createRoom" class="weui-btn weui-btn_primary" style="display:none">开始直播(房号:@Model.id)</button>
                            <button type="button" id="leaveRoom" class="weui-btn weui-btn_warn" style="display:none">退出房间</button>
                            <button type="button" id="endJoinLive" class="weui-btn weui-btn_warn"style="display:none">结束连麦</button>
                            <button type="button" id="inviteJoinLive" class="weui-btn weui-btn_disabled"style="display:none">邀请连麦</button>
                            <button type="button" id="openRoom" class="weui-btn weui-btn_primary">打开房间(房号:@Model.user_id)</button>
                            <button type="button" id="endLive" class="weui-btn weui-btn_warn" >结束连麦</button>
                            <button type="button" id="requestJoinLive" class="weui-btn weui-btn_primary">请求连麦</button>

                        </div>
                    </div>


                    <!-- Button trigger modal -->
                    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" id="liveConfirm" style="display:none">
                        连麦弹窗
                    </button>

                    <!-- Modal -->
                    <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
                        <div class="modal-dialog" role="document">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <strong class="text-gray-dark" id="exampleModalLabel">收到连麦请求</strong>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary btn-sm" id="liveRefuse" data-dismiss="modal">拒绝连麦</button>
                                    <button type="button" class="btn btn-primary btn-sm" id="liveAgree" data-dismiss="modal">同意连麦</button>
                                </div>
                            </div>
                        </div>
                    </div>


                </div>
            </div>

            <!--/直播功能-->

        </div>

        <!--版权信息-->
        @await Html.PartialAsync("~/Areas/Web/Views/Shared/_Copyright.cshtml")
        <!--/版权信息-->
        <!--底部导航-->
        <div class="weui-tab foot-nav">
            <div class="weui-tab__panel">

            </div>
            <div class="weui-tabbar">
                <a asp-area="Web" asp-controller="Index" asp-action="Index" class="weui-tabbar__item">
                    <i class="iconfont icon-home weui-tabbar__icon"></i>
                    <p class="weui-tabbar__label">首页</p>
                </a>
                <a asp-area="Web" asp-controller="Video" asp-action="Index" class="weui-tabbar__item">
                    <i class="iconfont icon-video weui-tabbar__icon"></i>
                    <p class="weui-tabbar__label">大厅</p>
                </a>
            </div>
        </div>
        <!--/底部导航-->
    </div>
</body>
<script>
    var txtMsg = document.getElementById("txtMsg");
    var btnSend = document.getElementById("btnSend");
    btnSend.disabled = true;

    var connection = new signalR.HubConnectionBuilder().withUrl("/NoticeHub").build();
    connection.on("OnLive", function (date, message) {
        var msg = message;
        var li = document.createElement("li");
        li.textContent = msg;
        document.getElementById("msgs").appendChild(li);

        var ul = document.querySelector("#msgs");
        var lis = ul.querySelectorAll("li");
        if (lis.length > 5) {
            lis[0].remove();
        }

    });

    connection.start().then(function () {
        btnSend.disabled = false;
    }).catch(function (err) {
        alert(err);
    });

    btnSend.onclick = function () {
        if (txtMsg.value.length < 1 || txtMsg.value.length > 20) {
            alert('文字大于1小于20');
            return;
        }        
        var msgvalue ='@ViewBag.username'+"说:" + txtMsg.value;
        connection.invoke("LiveMessage", msgvalue)
            .then(function () {
                txtMsg.value = "";
                txtMsg.focus();
            })
            .catch(function (err) {
                alert(err);
            });
    };
</script>
<!--zjego-->
<script src="/zjego/assets/jquery-3.3.1.min.js"></script>
<script src="/zjego/assets/popper.min.js"></script>
<script src="/zjego/assets/bootstrap.min.js"></script>
<!-- zego js sdk -->
<script src="/zjego/assets/jZego-rtc.js"></script>
<script>
   var zg,
    appid = getParamByName('appid') || 3358795986, // 必填，应用id，请从 即构管理控制台-https://console.zego.im/acount/register 或邮件中获取
    appSigin = '0x87,0x5b,0x8d,0x73,0x5e,0x18,0xb0,0x1d,0x03,0x46,0xcc,0x20,0xe9,0x8c,0xfc,0x23,0x50,0x79,0x4b,0x71,0x47,0x5c,0x62,0xe6,0x7e,0x8a,0xdb,0xac,0x0d,0x8b,0x98,0xfc', // appSigin为即构给客户分配的秘钥，请勿泄漏；（测试环境下是生成token的密码，必填，正式环境需要放到服务端）
    _config = {
        appid: appid * 1,
        idName: new Date().getTime() + '',
        nickName: '@ViewBag.username',//'u' + new Date().getTime(),
        server: 'wss://webliveroom-test.zego.im/ws',//必填，接入服务器地址，请从 即构管理控制台-https://console.zego.im/acount/register 或邮件中获取
        logLevel: 0,
        logUrl: "",
        remoteLogLevel: 0,
        audienceCreateRoom: true
    },
    _otherConfig = {
        cgi_token: '',
        roomlist: '',
        signal: '',
        token: "https://wsliveroom-demo.zego.im:8282/token"//"https://wsliveroom"+appid+"-api.zego.im:8282/token",
    },
    loginRoom = false,
    previewVideo,
    screenCaptrue,
    isPreviewed = false,
    useLocalStreamList = [];
var anchor_userid = '', anchro_username = '';


$(function () {
    console.log('sdk version is', ZegoClient.getCurrentVersion());
    // if (ZegoClient.isSupportWebrtc()) {
    //     ZegoClient.isSupportH264(result => {
    //         bindEvent();
    //         if (!result) {
    //             alert('浏览器不支持视频h264编码，建议使用vp8尝试');
    //         }
    //     }, err => {
    //         console.error(err);
    //     })
    // } else {
    //     alert('浏览器不支持webrtc，换一个浏览器试试吧');
    // }
    ZegoClient.supportDetection(result => {
        console.log(result);
        bindEvent();
    }, err => {
        alert(err);
    })

    desc()

});

function getBrowser() {
    var ua = window.navigator.userAgent;
    var isIE = window.ActiveXObject != undefined && ua.indexOf("MSIE") != -1;
    var isFirefox = ua.indexOf("Firefox") != -1;
    var isOpera = window.opr != undefined;
    var isChrome = ua.indexOf("Chrome") && window.chrome;
    var isSafari = (ua.indexOf("Safari") != -1 && ua.indexOf("Version") != -1) || ua.indexOf('iPhone') != -1;
    if (isIE) {
        return "IE";
    } else if (isFirefox) {
        return "Firefox";
    } else if (isOpera) {
        return "Opera";
    } else if (isChrome) {
        return "Chrome";
    } else if (isSafari) {
        return "Safari";
    } else {
        return "Unkown";
    }
}


function IsPC() {
    var userAgentInfo = navigator.userAgent;
    var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    return flag;
}

function enumDevices() {
    var audioInputList = [], videoInputList = [];
    zg.enumDevices(deviceInfo => {
        console.log('enumDevices' + JSON.stringify(deviceInfo));
        if (deviceInfo.microphones) {
            for (var i = 0; i < deviceInfo.microphones.length; i++) {

                if (!deviceInfo.microphones[i].label) {
                    deviceInfo.microphones[i].label = 'microphone' + i;
                }
                audioInputList.push(' <option value="' + deviceInfo.microphones[i].deviceId + '">' + deviceInfo.microphones[i].label + '</option>');
                console.log("microphone: " + deviceInfo.microphones[i].label);
            }
        }

        if (deviceInfo.cameras) {
            for (var i = 0; i < deviceInfo.cameras.length; i++) {
                if (!deviceInfo.cameras[i].label) {
                    deviceInfo.cameras[i].label = 'camera' + i;
                }
                videoInputList.push('<option value="' + deviceInfo.cameras[i].deviceId + '">' + deviceInfo.cameras[i].label + '</option>');
                console.log("camera: " + deviceInfo.cameras[i].label);
            }
        }

        audioInputList.push(' <option value="0">禁止</option>');
        videoInputList.push('<option value="0">禁止</option>');

        $('#audioList').html(audioInputList.join(''));
        $('#videoList').html(videoInputList.join(''));
    }, function (error) {
        console.error("enum device error: " + error);
    });
}


function getParamByName(key) {
    var search = location.search;

    if (!search || search == '?') return null;
    search = search.replace('?', '');

    var param_arr = search.split('&'), param_map = {};
    param_arr.forEach(function (item) {
        var _key = item.split('=')[0], value = item.split('=')[1];
        param_map[_key] = value;
    });

    return param_map[key];
}

function openRoom(roomId, type) {

    if (!roomId) {
        alert('请输入房间号');
        return;
    }   
    screenCaptrue && zg.stopScreenShot();


    //get token   生产环境下获取token方式
    if (!appSigin) {
        $.get(_otherConfig.token, {app_id: _config.appid, id_name: _config.idName, cgi_token: _otherConfig.cgi_token},
            function (token) {
                if (!token) {
                    alert('get token failed')
                } else {
                    console.log('gettoken success');
                    startLogin(roomId, token, type)
                }
            }, 'text');

    } else {//get token  前端开发绕过后端，临时获取token方式，需要填写appSign
        var now = new Date().getTime();
        $.get('https://sig-wstoken.zego.im:8282/tokenverify',
            {
                app_id: _config.appid,
                id_name: _config.idName,
                app_secret: appSigin,
                nonce: now,
                expired: Math.floor(now / 1000 + 30 * 60)
            },
            function (token) {
                token = /token:(.+)/.exec(token) && /token:(.+)/.exec(token)[1] && /token:(.+)/.exec(token)[1].replace(' ', '');

                if (!token) {
                    alert('get token failed')
                } else {
                    console.log('gettoken success');
                    startLogin(roomId, token, type)
                }
            });
    }
}


//login
function startLogin(roomId, token, type) {
    zg.login(roomId, type, token, function (streamList) {
        console.log('login success');
        loginSuccess(streamList, type);
    }, function (err) {
        loginFailed(err);
    })
}

function loginFailed(err) {
    alert('登录失败');
    console.error(err)

}

function loginSuccess(streamList, type) {
    var maxNumber = ($('#maxPullNamber') && $('#maxPullNamber').val()) || 4

    //限制房间最多人数，原因：视频软解码消耗cpu，浏览器之间能支撑的个数会有差异，太多会卡顿
    if (streamList.length >= maxNumber) {
        alert('房间太拥挤，换一个吧！');
        leaveRoom();
        return;
    }
    if ($('#streamID').val()) {
        useLocalStreamList = [{
            anchor_id_name: 'custom',
            stream_id: $('#streamID').val(),
            anchor_nick_name: 'custom'
        }, ...streamList];
    } else {
        useLocalStreamList = streamList;
    }


    $('.remoteVideo').html('');
    $('#memberList').html('');
    for (var index = 0; index < useLocalStreamList.length; index++) {
        $('.remoteVideo').append($('<video  autoplay muted playsinline controls></video>'));
        $('#memberList').append('<option value="' + useLocalStreamList[index].anchor_id_name + '">' + useLocalStreamList[index].anchor_nick_name + '</option>');
        play(useLocalStreamList[index].stream_id, $('.remoteVideo video:eq(' + index + ')')[0]);
    }
    console.log(`login success`);

    loginRoom = true;


    //开始预览本地视频
    type === 1 && doPreviewPublish();

}

//预览
function doPreviewPublish(config) {
    var quality = ($('#videoQuality') && $('#videoQuality').val()) || 2;

    var previewConfig = {
        "audio": $('#audioList').val() === '0' ? false : true,
        "audioInput": $('#audioList').val() || null,
        "video": $('#videoList').val() === '0' ? false : true,
        "videoInput": $('#videoList').val() || null,
        "videoQuality": quality * 1,
        "horizontal": true,
        "externalCapture": false,
        "externalMediaStream": null
    };
    previewConfig = $.extend(previewConfig, config);
    console.log('previewConfig', previewConfig);
    var result = zg.startPreview(previewVideo, previewConfig, function () {
        console.log('preview success');
        isPreviewed = true;
        $('#previewLabel').html(_config.nickName);
        publish();
        //部分浏览器会有初次调用摄像头后才能拿到音频和视频设备label的情况，
        if (!$('#videoList').val() && $('#videoList').val() == 0) {
            enumDevices();
        }
    }, function (err) {
        alert(JSON.stringify(err));
        console.error('preview failed', err);
    });

    if (!result) alert('预览失败！')
}

//推流
function publish() {
    var videoCodeType = $('#videoCodeType').val();
    zg.startPublishingStream(_config.idName, previewVideo, null, {videoDecodeType: videoCodeType ? videoCodeType : 'H264'});

}

function play(streamId, video) {
    var playVideoCodeType = $('#videoPlayCodeType').val()
    var result = zg.startPlayingStream(streamId, video, null, {videoDecodeType: playVideoCodeType ? playVideoCodeType : 'H264'});

    video.muted = false;
    if (!result) {
        alert('哎呀，播放失败啦');
        video.style = 'display:none';
        console.error("play " + el.nativeElement.id + " return " + result);

    }
}


function listen() {
    var _config = {
        onPlayStateUpdate: function (type, streamid, error) {
            if (type == 0) {
                console.info('play  success');
            } else if (type == 2) {
                console.info('play retry');
            } else {

                console.error("play error " + error.msg);

                var _msg = error.msg;
                if (error.msg.indexOf('server session closed, reason: ') > -1) {
                    var code = error.msg.replace('server session closed, reason: ', '');
                    if (code == 21) {
                        _msg = '音频编解码不支持(opus)';
                    } else if (code == 22) {
                        _msg = '视频编解码不支持(H264)'
                    } else if (code == 20) {
                        _msg = 'sdp 解释错误';
                    }
                }
                alert('拉流失败,reason = ' + _msg);
            }

        },
        onPublishStateUpdate: function (type, streamid, error) {
            if (type == 0) {
                console.info(' publish  success');
            } else if (type == 2) {
                console.info(' publish  retry');
            } else {
                console.error('publish error ' + error.msg);
                var _msg = error.msg;
                if (error.msg.indexOf('server session closed, reason: ') > -1) {
                    var code = error.msg.replace('server session closed, reason: ', '');
                    if (code == 21) {
                        _msg = '音频编解码不支持(opus)';
                    } else if (code == 22) {
                        _msg = '视频编解码不支持(H264)'
                    } else if (code == 20) {
                        _msg = 'sdp 解释错误';
                    }
                }
                alert('推流失败,reason = ' + _msg);

            }

        },
        onPublishQualityUpdate: function (streamid, quality) {
            console.info("#" + streamid + "#" + "publish " + " audio: " + quality.audioBitrate + " video: " + quality.videoBitrate + " fps: " + quality.videoFPS);
        },

        onPlayQualityUpdate: function (streamid, quality) {
            console.info("#" + streamid + "#" + "play " + " audio: " + quality.audioBitrate + " video: " + quality.videoBitrate + " fps: " + quality.videoFPS);
        },

        onDisconnect: function (error) {
            console.error("onDisconnect " + JSON.stringify(error));
            alert('网络连接已断开' + JSON.stringify(error));
            leaveRoom();
        },

        onKickOut: function (error) {
            console.error("onKickOut " + JSON.stringify(error));
        },
        onStreamUpdated: function (type, streamList) {
            if (type == 0) {
                for (var i = 0; i < streamList.length; i++) {
                    console.info(streamList[i].stream_id + ' was added');
                    useLocalStreamList.push(streamList[i]);
                    $('#memberList').append('<option value="' + streamList[i].anchor_id_name + '">' + streamList[i].anchor_nick_name + '</option>');
                    $('.remoteVideo').append($('<video  autoplay muted playsinline controls></video>'));
                    play(streamList[i].stream_id, $('.remoteVideo video:last-child')[0]);
                }

            } else if (type == 1) {

                for (var k = 0; k < useLocalStreamList.length; k++) {

                    for (var j = 0; j < streamList.length; j++) {

                        if (useLocalStreamList[k].stream_id === streamList[j].stream_id) {

                            zg.stopPlayingStream(useLocalStreamList[k].stream_id);

                            console.info(useLocalStreamList[k].stream_id + 'was devared');

                            useLocalStreamList.splice(k, 1);

                            $('.remoteVideo video:eq(' + k + ')').remove();
                            $('#memberList option:eq(' + k + ')').remove();

                            break;
                        }
                    }
                }
            }

        }
    };

    for (var key in _config) {
        zg[key] = _config[key]
    }

    if (typeof listenChild === 'function') {
        listenChild();
    }

}


function leaveRoom() {
    console.info('leave room  and close stream');

    if (isPreviewed) {
        zg.stopPreview(previewVideo);
        zg.stopPublishingStream(_config.idName);
        isPreviewed = false;
    }

    for (var i = 0; i < useLocalStreamList.length; i++) {
        zg.stopPlayingStream(useLocalStreamList[i].stream_id);
    }

    useLocalStreamList = [];
    $('.remoteVideo').html('');
    $('.chatBox-content-demo').html('');
    $('.chat-message-num').text(0)
    zg.logout();
}


function init() {

    zg = new ZegoClient();

    //内调测试用代码，客户请忽略  start
    setConfig(zg);
    //内调测试用代码，客户请忽略  end

    zg.config(_config);
    enumDevices();

    // 监听sdk回掉
    listen();


}


function bindEvent() {
    previewVideo = $('#previewVideo')[0];

    //初始化sdk
    init();

    $('#createRoom').click(function () {
        $('#signalUrl').val() && zg.setCustomSignalUrl($('#signalUrl').val())
        zg.setUserStateUpdate(true);
        openRoom($('#roomId').val(), 1);
    });

    $('#openRoom').click(function () {
        openRoom($('#roomId').val(), 2);
    });


    $('#leaveRoom').click(function () {
        leaveRoom();
    });

    $('#switchVideo').click(function () {
        zg.switchDevice('video', $('#previewVideo')[0], $('#videoList').val(), () => {
            console.warn('switch camera success')
        }, err => {
            console.error(err)
        })
    });

    $('#switchAudio').click(function () {
        zg.switchDevice('audio', $('#previewVideo')[0], $('#audioList').val(), () => {
            console.warn('switch audio success')
        }, err => {
            console.error(err)
        })
    })


    //防止，暴力退出（关闭或刷新页面）--最新版本已经内部集成 不再需要
    // var isOnIOS = navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPhone/i);
    // var eventName = isOnIOS ? "pagehide" : "beforeunload";
    // window.addEventListener(eventName, function (event) {
    //     window.event.cancelBubble = true; // Don't know if this works on iOS but it might!
    //     leaveRoom();
    // });

}

function onDeviceReady() {
    var permissions = cordova.plugins.permissions;
    permissions.checkPermission(permissions.CAMERA, function (status) {
        if (status.hasPermission) {
            console.log("Yes :D ");
        } else {
            console.warn("No :( ");
        }
    });
    permissions.requestPermissions([permissions.CAMERA, permissions.RECORD_AUDIO], function (status) {
        console.log("requestPermissions: ", status);
    }, function (err) {
        console.error("requestPermissions: ", err);
    })
}


function setConfig(zg) {
    //测试用代码，客户请忽略  start
    if (location.search) {
        let _arr_config = location.search.substr(1).split('&');
        _arr_config.forEach(function (item) {
            var key = item.split('=')[0], value = item.split('=')[1];

            if (value && _config.hasOwnProperty(key)) {
                _config[key] = decodeURIComponent(value);
            } else if (value && _otherConfig.hasOwnProperty(key)) {
                _otherConfig[key] = decodeURIComponent(value);
            }
        });
    }
    //测试用代码，客户请忽略  end


    console.log("config param:" + JSON.stringify(_config));

    _config.appid = _config.appid * 1;
    _config.testEnvironment = !!(_config.testEnvironment * 1);

    //测试用代码，客户请忽略  start
    if (_otherConfig.signal) {
        zg.setCustomSignalUrl(_otherConfig.signal);
    }

    if (_otherConfig.cgi_token && _otherConfig.token == 'https://wsliveroom-demo.zego.im:8282/token') {
        $.get(_otherConfig.cgi_token, function (cgi_token) {
            _otherConfig.cgi_token = cgi_token.data;
            console.log(_otherConfig.cgi_token);
        })
    }
    //测试用代码，客户请忽略  end
}

function addCssByLink(url) {
    var doc = document;
    var link = doc.createElement("link");
    link.setAttribute("rel", "stylesheet");
    link.setAttribute("type", "text/css");
    link.setAttribute("href", url);

    var heads = doc.getElementsByTagName("head");
    if (heads.length)
        heads[0].appendChild(link);
    else
        doc.documentElement.appendChild(link);
}

function loadJs(url, callback) {
    var script = document.createElement('script');
    script.type = "text/javascript";
    if (typeof (callback) != "undefined") {
        if (script.readyState) {
            script.onreadystatechange = function () {
                if (script.readyState == "loaded" || script.readyState == "complete") {
                    script.onreadystatechange = null;
                    callback();
                }
            }
        } else {
            script.onload = function () {
                callback();
            }
        }
    }
    script.src = url;
    document.body.appendChild(script);
}

function desc() {
    addCssByLink('/zjego/assets/desc.css');

    loadJs('/zjego/assets/desc.js', function () {
        var descAtag = document.createElement('a');
        descAtag.setAttribute('id', 'descModule');
        descAtag.setAttribute('role', 'button');
        descAtag.setAttribute('tabindex', '0');
        // descAtag.setAttribute('data-trigger', 'focus');
        descAtag.setAttribute('data-toggle', 'popover');
        descAtag.setAttribute('title', '调用说明');

        var pageUrl = location.pathname.split('/');
        pageUrl = pageUrl[pageUrl.length - 2];
        var descArr = descObj[pageUrl] || [];
        descAtag.setAttribute('data-content', descArr.join(`<br/><br/>`));

        console.log(descObj);
        document.getElementsByTagName('body')[0].appendChild(descAtag);

        $('#descModule').popover({
            html: true
        })
    })
}


function addCssByLink(url) {
    var doc = document;
    var link = doc.createElement("link");
    link.setAttribute("rel", "stylesheet");
    link.setAttribute("type", "text/css");
    link.setAttribute("href", url);

    var heads = doc.getElementsByTagName("head");
    if (heads.length)
        heads[0].appendChild(link);
    else
        doc.documentElement.appendChild(link);
}

function loadJs(url, callback) {
    var script = document.createElement('script');
    script.type = "text/javascript";
    if (typeof (callback) != "undefined") {
        if (script.readyState) {
            script.onreadystatechange = function () {
                if (script.readyState == "loaded" || script.readyState == "complete") {
                    script.onreadystatechange = null;
                    callback();
                }
            }
        } else {
            script.onload = function () {
                callback();
            }
        }
    }
    script.src = url;
    document.body.appendChild(script);
}

function desc() {
    addCssByLink('/zjego/assets/desc.css');
    loadJs('/zjego/assets/desc.js', function () {
        var descAtag = document.createElement('a');
        descAtag.setAttribute('id', 'descModule');
        descAtag.setAttribute('role', 'button');
        descAtag.setAttribute('tabindex', '0');
        // descAtag.setAttribute('data-trigger', 'focus');
        descAtag.setAttribute('data-toggle', 'popover');
        descAtag.setAttribute('title', '调用说明');

        var pageUrl = location.pathname.split('/');
        pageUrl = pageUrl[pageUrl.length - 2];

        var descArr = descObj[pageUrl] || [];
        descAtag.setAttribute('data-content', descArr.join(`<br/><br/>`));

        console.log(descObj);
        document.getElementsByTagName('body')[0].appendChild(descAtag);

        $('#descModule').popover({
            html: true
        })
    })
}

// cordova test
(function cordovaLoad() {
    if (location.search && location.search.indexOf('platform=cordova') > -1) {
        loadJs('/zjego/assets/cordova.js');
        document.addEventListener('deviceready', function () {
            var permissions = cordova.plugins.permissions;
            permissions.checkPermission(permissions.CAMERA, function (status) {
                if (status.hasPermission) {
                    console.log("Yes :D ");
                } else {
                    permissions.requestPermissions([permissions.CAMERA, permissions.RECORD_AUDIO], function (status) {
                        console.log("requestPermissions: ", status);
                    }, function (err) {
                        console.error("requestPermissions: ", err);
                    })
                    console.warn("No :( ");
                }
            });
        }, false);
    }
})();



</script>
<script>
            var role = null  //角色
            //覆盖index.js 中的init
            function init() {
                zg = new ZegoClient();
                zg.setUserStateUpdate(true);//重要  启动用户变化监听

                //内调测试用代码，客户请忽略  start
                setConfig(zg);
                //内调测试用代码，客户请忽略  end


                zg.config(_config);
                enumDevices();

                // 监听sdk回掉
                listen();
            }

            function respondJoinLive(flag, requestId, fromUserId) {
                var accept = flag;
                window._fromUserId = fromUserId;
                zg.respondJoinLive(requestId, accept, function (seq) {
                    console.log('respondJoinLive success', seq);
                }, function (err, seq) {
                    console.log('respondJoinLive err', err, seq);
                })
            }

            function listenChild() {
                var listens = {
                    onGetAnchorInfo: function (userid, username) {
                        anchor_userid = userid, anchro_username = username;
                    },

                    onRecvJoinLiveRequest: function (requestId, from_userid, from_username, roomid) {
                        console.log('onRecvJoinLiveRequest', requestId, from_userid, from_username, roomid);
                        $('#exampleModalLabel').text("收到id为" + requestId + "的连麦请求")
                        $('#liveConfirm').click();
                        $('#liveAgree').on('click', function () {
                            respondJoinLive(true, requestId, from_userid)
                        })
                        $('#liveRefuse').on('click', function () {
                            respondJoinLive(false, requestId, from_userid)
                        })
                    },

                    onRecvInviteJoinLiveRequest: function (requestId, from_userid, from_username, roomid) {
                        console.log('onRecvInviteJoinLiveRequest', requestId, from_userid, from_username, roomid);
                        $('#exampleModalLabel').text("收到id为" + requestId + "的连麦请求")
                        $('#liveConfirm').click();
                        $('#liveAgree').on('click', function () {
                            doPreviewPublish()
                        })
                    },

                    onRecvEndJoinLiveCommand: function (requestId, from_userid, from_username, roomid) {
                        console.log('onRecvEndJoinLiveCommand', requestId, from_userid, from_username, roomid);
                        isPreviewed && zg.stopPreview(previewVideo);
                        isPreviewed && zg.stopPublishingStream(_config.idName);
                    },
                    onUserStateUpdate: function (roomId, userList) {
                        console.log('onUserStateUpdate', roomId, userList);
                        userList.forEach(function (item) {
                            if (item.action === 1) {
                                $userList.push(item);
                            } else if (item.action === 2) {
                                $userList.forEach(function (item2, index) {
                                    if (item.idName === item2.idName) {
                                        $userList.splice(index, 1)
                                    }
                                })
                            }


                        })
                        $('#memberList').html('');
                        $userList.forEach(function (item) {
                            item.idName !== window._config.idName && $('#memberList').append('<option value="' + item.idName + '">' + item.nickName + '</option>');
                        });
                    },
                    onGetTotalUserList: function (roomId, userList) {
                        $userList = userList;
                        $('#memberList').html('');
                        $userList.forEach(function (item) {
                            item.idName !== window._config.idName && $('#memberList').append('<option value="' + item.idName + '">' + item.nickName + '</option>');
                        });
                        console.log('onGetTotalUserList', roomId, userList);
                    }
                };
                for (var key in listens) {
                    zg[key] = listens[key]
                }
            }

            function loginSuccess(streamList, type) {

                let role = zg.stateCenter.role

                if (role == 1) {
                    $('#endLive')[0].disabled = true
                    $('#requestJoinLive')[0].disabled = true
                } else if (role == 2) {
                    $('#endJoinLive')[0].disabled = true
                    $('#inviteJoinLive')[0].disabled = true
                }


                var maxNumber = ($('#maxPullNamber') && $('#maxPullNamber').val()) || 4

                //限制房间最多人数，原因：视频软解码消耗cpu，浏览器之间能支撑的个数会有差异，太多会卡顿
                if (streamList.length >= maxNumber) {
                    alert('房间太拥挤，换一个吧！');
                    leaveRoom();
                    return;
                }
                if ($('#streamID').val()) {
                    useLocalStreamList = [{
                        anchor_id_name: 'custom',
                        stream_id: $('#streamID').val(),
                        anchor_nick_name: 'custom'
                    }, ...streamList];
                } else {
                    useLocalStreamList = streamList;
                }


                $('.remoteVideo').html('');
                $('#memberList').html('');
                for (var index = 0; index < useLocalStreamList.length; index++) {
                    $('.remoteVideo').append($('<video  autoplay muted playsinline controls></video>'));
                    $('#memberList').append('<option value="' + useLocalStreamList[index].anchor_id_name + '">' + useLocalStreamList[index].anchor_nick_name + '</option>');
                    play(useLocalStreamList[index].stream_id, $('.remoteVideo video:eq(' + index + ')')[0]);
                }
                console.log(`login success`);

                loginRoom = true;


                //开始预览本地视频
                type === 1 && doPreviewPublish();

            }

            function leaveRoom() {
                console.info('leave room  and close stream');

                if (isPreviewed) {
                    zg.stopPreview(previewVideo);
                    zg.stopPublishingStream(_config.idName);
                    isPreviewed = false;
                }

                for (var i = 0; i < useLocalStreamList.length; i++) {
                    zg.stopPlayingStream(useLocalStreamList[i].stream_id);
                }

                $('#endLive')[0].disabled = false
                $('#requestJoinLive')[0].disabled = false
                $('#endJoinLive')[0].disabled = false
                $('#inviteJoinLive')[0].disabled = false

                useLocalStreamList = [];
                $('.remoteVideo').html('');
                zg.logout();

                role = null
            }


            $(function () {
                $('#requestJoinLive').click(function () {
                    anchor_userid && zg.requestJoinLive(anchor_userid, function (seq) {
                        console.log('requestJoinLive suc', seq);
                    }, function (err, seq) {
                        console.log('requestJoinLive err', err, seq);
                    }, function (result, fromUserId, fromUserName) {
                        window._fromUserId = fromUserId;
                        // alert(result ? '同意连麦' : '拒绝连麦');
                        $('#exampleModalLabel').text("收到id为" + fromUserName + "的连麦请求")
                        $('#liveConfirm').click();
                        $('#liveAgree').on('click', function () {
                            doPreviewPublish()
                            console.log('requestJoinLive callback', result, fromUserId, fromUserName);
                        })
                    })
                });

                $('#endLive').click(function () {
                    isPreviewed && zg.stopPreview(previewVideo);
                    isPreviewed && zg.stopPublishingStream(_config.idName);
                });


                $('#endJoinLive').click(function () {
                    window._fromUserId && zg.endJoinLive(window._fromUserId, function (seq) {
                        console.log('requestJoinLive suc', seq);
                    }, function (err, seq) {
                        console.log('requestJoinLive err', err, seq);
                    });
                    zg.stopPlayingStream(window._fromUserId);
                    $('.remoteVideo').html('');
                })

                $('#inviteJoinLive').click(function () {
                    $('#memberList').val() && zg.inviteJoinLive($('#memberList').val(), function (seq) {
                        window._fromUserId = $('#memberList').val();
                        console.log('inviteJoinLive suc', seq);
                    }, function (err, seq) {
                        console.log('inviteJoinLive err', err, seq);
                    }, function (result, fromUserId, fromUserName) {
                        alert('同意连麦');
                        doPreviewPublish();
                        console.log('inviteJoinLive callback', result, fromUserId, fromUserName);
                    })
                })

            });

</script>
<!--/zjego-->
</html>
